package cn.jiyun.gateway.filter;

import cn.jiyun.gateway.properties.FilterProperties;
import cn.jiyun.gateway.properties.JwtProperties;
import com.jiyun.leyou.pojo.UserInfo;
import com.jiyun.leyou.util.JwtUtils;
import com.leyou.common.util.CookieUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
// @EnableConfigurationProperties  调用的时候才会运行
public class UserFilter extends ZuulFilter {

    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    FilterProperties filterProperties;

    // 过滤器的类型，路由 。前置过滤器，pre，后置过滤器，post，运行过滤器，route，err
    @Override
    public String filterType() {
        return "pre";
    }

    // 过滤器的级别，越小级别越高
    @Override
    public int filterOrder() {
        return 20;
    }

    // 是否进行过滤
    @Override
    public boolean shouldFilter() {
        // 白名单信息
        // 获取URL，判断URL中的路径上是否包含报名单的信息
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        // 获取请求的url
        String url = request.getRequestURI();
        // 与限定好的白名单路径进行匹配   http://api.leyou.com/api/user/check
        List<String> allowPaths = filterProperties.getAllowPaths();
        for (String allowPath : allowPaths) {
            if(url.contains(allowPath)){
                return false;
            }
        }
        return true;
    }

    // 过滤之后运行的代码
    @Override
    public Object run() throws ZuulException {

        // token来自于Cookie？Cookie来自于request？
        // 通过Zuul获取，上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();

        HttpServletRequest request = requestContext.getRequest();

        String token = CookieUtils.getCookieValue(request, "LY_TOKEN");

        // 进行登录的验证
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if(userInfo==null){
                // 不允许
                requestContext.setSendZuulResponse(false);
                // 响应状态码
                requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
                // 响应错误信息
                requestContext.setResponseBody("{\"status\":\"401\", \"text\":\"request error!\"}");

            }


        } catch (Exception e) {
            e.printStackTrace();
            // 不允许
            requestContext.setSendZuulResponse(false);
            // 响应状态码
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            // 响应错误信息
            requestContext.setResponseBody("{\"status\":\"401\", \"text\":\"request error!\"}");

        }


        return null;
    }
}
